import React, { useCallback, useEffect, useState } from 'react'
import { List, Tag, Space, PullToRefresh, InfiniteScroll, Button, Toast, Divider, Ellipsis } from 'antd-mobile'
import http from '../helper/http'
import { PageModel } from '@/models/PageModel'
import wcheader from './WorkCountFC/WorkCountHeader'
import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'
import qs from 'qs'
import { TaskModel } from '@/models/TaskModel'
import ClipboardJS from 'clipboard';

export default (props: { mode: 'all' | 'mine' }) => {
    const groupby = { all: ['YYYY-MM'], mine: ['YYYY-MM-DD'] }[props.mode] ?? ['YYYY-MM']
    const keywords = { all: '', mine: localStorage.getItem('username') }[props.mode] ?? ''
    const dt1date = dayjs().date(1).toDate()
    const dt2date = dayjs().date(1).add(1, 'month').add(-1, 'day').toDate()

    const [page, setPage] = useState<PageModel>({ page: 1, size: 20, groupby, keywords, date1: dt1date, date2: dt2date })

    const [list, setList] = useState<TaskModel[]>([]);
    const [hasMore, setHasMore] = useState(true)

    const loadData = () => {

        const params = Object.assign({}, page, {
            keywords: encodeURI(page.keywords),
            CURR_USER_TYPE: encodeURI('我的所有待办'),
            sidx: 'CREATE_TIME', // encodeURI('CREATE_TIME'),
            sort: 'desc'
        })

        // 如果是从排名界面进来的
        const hashstr = location.hash;
        const param = hashstr.slice(hashstr.indexOf('?') + 1)
        const queryParam = qs.parse(param) as { dept: string, name: string, day: string }
        if (queryParam.name) {
            params.keywords = encodeURI(queryParam.name)
        }

        const fmtDate = (str: string) => {
            const dt2 = str.replace('/Date(', '').replace(')/', '') ?? '';
            const dt3 = parseInt(dt2, 10);
            if (dt3)
                return dayjs(dt3).format('YYYY-MM-DD HH:mm:ss');
            return '未填写'
        }


        return http.get('/task-list', { params }).then(res => {
            const data = res.data
            setHasMore(data.rows.length === page.size)

            data.rows.forEach((el: TaskModel) => {
                el.研发要求时间 = fmtDate(el.研发要求时间 ?? '')
                el.产品承诺时间 = fmtDate(el.产品承诺时间 ?? '')
                el.要求完成时间 = fmtDate(el.要求完成时间 ?? '')
            });

            return Promise.resolve(data)
        });
    }

    // useEffect(() => {
    //     onRefresh();
    // }, [])

    const onRefresh = () => {
        page.page = 1

        setPage(page)

        return loadData().then((res) => {
            setList(res.rows)
        })
    }

    const onSearch = (param: PageModel) => {
        page.keywords = param.keywords
        page.groupby = param.groupby
        page.date1 = param.date1
        page.date2 = param.date2
        page.page = 1
        setPage(page)
        return loadData().then((res) => {
            setList(res.rows)
        })
    }

    const loadMore = (isRetry: boolean): Promise<void> => {
        if (list.length === 0) {
            page.page = 1
        } else {
            page.page += 1
        }
        setPage(page)

        return loadData().then((res) => {
            setList([...list, ...res.rows])
        })
    }

    useEffect(() => {
        new ClipboardJS('.copyBusiness');
    }, [])

    const headertitle = '我的待办'
    return (
        <>
            <PullToRefresh onRefresh={onRefresh}>
                <List mode='default'
                    header={
                        wcheader(headertitle, props.mode, page, (param => {
                            onSearch(param)
                        }))
                    }>
                    {list.map((item, index: number) => (
                        <List.Item key={index} extra='' clickable={false}>
                            <Space>
                                <Tag color='primary' style={{ '--border-radius': '50%' }}>{index + 1}</Tag>
                                <Button className='copyBusiness' onClick={
                                    () => {
                                        Toast.show({
                                            content: '复制成功',
                                        })
                                    }
                                } color='primary' fill='none' size='mini' data-clipboard-text={item.BUSINESS_ID}>{item.BUSINESS_ID} | 复制</Button>

                                <Tag>工单状态：{item.STATUS_NAME}</Tag>

                            </Space>

                            <p>
                                <Space>
                                    <Tag color='danger'>{`${item.过期天数 ?? '未过期'}`}</Tag>
                                    <Tag color='success'>研发点数:{item.研发点数}</Tag>
                                </Space>
                            </p>
                            <p style={{ color: '#3d3d3d', fontSize: '14px' }}>
                                当前步骤：{item.CURR_STEP_NAME} / {item.CURR_USER_NAME}「{item.CURR_USER_TYPE}」
                                <br /> <br />
                                工单发起人：{item.ORIGINATOR_USERNAME}
                            </p>

                            <Divider contentPosition='left'>要求时间</Divider>
                            <p style={{ color: '#9d9d9d', fontSize: '14px' }}>
                                <Ellipsis
                                    direction='end'
                                    content={`要求完成时间:${item.要求完成时间} / 产品承诺时间:${item.产品承诺时间} / 研发要求时间:${item.研发要求时间}`}
                                    expandText='展开'
                                    collapseText='收起'
                                />
                            </p>

                            <Divider contentPosition='left'>问题描述</Divider>
                            <p style={{ color: '#9d9d9d', fontSize: '14px' }}>
                                <Ellipsis
                                    direction='end'
                                    content={item.问题描述 ?? ''}
                                    expandText='展开'
                                    collapseText='收起'
                                />
                            </p>

                        </List.Item>
                    ))}
                </List>
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </PullToRefresh>
        </>
    )
}